package ludowork.visorbasicplugins;

import ludowork.core.ImageSource;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import ludowork.core.Manager;
import ludowork.core.VisorPlugin;

public class ImageLoader implements ImageSource , VisorPlugin{

    public ImageLoader() {
        fc = new JFileChooser();
        FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("images", "png", "jpg", "jpeg", "bmp", "gif", "tif", "tiff");
        fc.setFileFilter(extensionFilter);
    }

    private void loadFile(File file) throws IOException {
        ImageInputStream iis = ImageIO.createImageInputStream(file);
        Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
        if (!readers.hasNext()) {
            //throw new UnsupportedOperationException("Cant find an adecuate image reader");
            Manager.getManager().getLogger().addLine("Cant find an adecuate image reader");
        }
        reader = readers.next();
        reader.setInput(iis);
    }

    @Override
    public int getSize() {
        try {
            return reader.getNumImages(true);
        } catch (IOException ex) {
            return 0;
        }
    }

    @Override
    public BufferedImage getImage(int i) {
        try {
            if ((i < reader.getNumImages(true)) && (i >= 0)) {
                return reader.read(i);
            } else {
                return null;
            }
        } catch (IOException ex) {
            return null;
        }
    }


    @Override
    public String getMenuName() {
        return "Open file";
    }

    @Override
    public int exec() {
        int returnVal = fc.showOpenDialog(null);
        switch (returnVal) {
            case JFileChooser.APPROVE_OPTION:
                try {
                    File file = fc.getSelectedFile();
                    loadFile(file);
                    Manager.getManager().setImageSource(this);
                    return Manager.SUCCESS;
                } catch (IOException ex) {
                    return Manager.FAILED;
                }
            case JFileChooser.CANCEL_OPTION:
                return Manager.CANCELED;
        }
        return Manager.FAILED;
    }

    private ImageReader reader;
    private JFileChooser fc;

}
